<!--  -->
<template>
  <div id="DigitalHuman f-12">
    <c-title text="上传数字人分身"></c-title>
    <div class="headTop flex-column">
      <div class="himg">
        <video :src="tempFilePath" v-if="tempFilePath" :controls="false" />
        <img :src="imgPath + 'ai-create/ai-create-07.png'" alt="" v-if="!tempFilePath" />
      </div>
      <van-button @click="chooseMedia" round type="info" color="var(--themeBaseColor)" style="width: 8.125rem;margin-top: 10px;height: 2.25rem;">{{
        tempFilePath ? "重新选择" : "上传视频"
      }}</van-button>

      <div style="display: none;">
        <van-uploader  :after-read="handleFileRead" ref="uploader" accept="video/*" />
      </div>
    </div>

    <div style="margin-top: -3rem;">
      <van-cell-group inset>
        <van-field v-model="name" label="分身名称" placeholder="请输入分身名称" :border="false" @input="onChange" />
      </van-cell-group>
      <van-cell-group inset custom-class='m-t-10 bg-fff' style="text-align: left;">
        <van-cell title="正脸参考图" :border="false" use-label-slot>
          <div slot="label">
            <div style="display: block;">
              <van-uploader v-model="fileList" use-before-read max-count="1" accept="image/jpeg, image/jpg, image/png, image/bmp, image/webp"   :after-read="uploadImage" bind:delete="onDelete"></van-uploader>
            </div>
            <div>注：如需在数字人视频创作中实现口型与音频相匹配的效
              果，请上传一张清晰的人物正脸，且为视频中出现的人
              物。若不输入人脸参考图，默认将选择视频中第一个有人
              脸的画面中，人脸占比最大的人物为目标。
            </div>
            <br>
            <div>
              图片要求：
              文件大小：小于等于10MB
              图像大小：长宽比小于等于 2，最大边长小于等 4096
              格式：jpeg、jpg、png、bmp、webp
            </div>
          </div>
        </van-cell>
      </van-cell-group>

      <van-cell-group inset class="m-t-10 bg-fff t-l">
        <van-cell title="视频要求" :border="false">
          <template #label>
            <div>文件大小:{{upload_file_tip}}</div>
            <div>视频时长:30s~300秒</div>
            <div>视频方向:横向或纵向</div>
            <div>视频格式：mp4、flv、mov、avi、wmv</div>
          </template>
        </van-cell>

        <div class="border-radius-10 bg-F8F8F8 padding-10 margin-10">
          <div class="f-13 color-F15353 f-bold">错误示例</div>
          <div class="gird-4">
            <div class="flex-column m-t-10" v-for="(item, index) in errDomo" :key="index">
              <img :src="imgPath + 'ai-create/ai-create-' + item.icon + '.png'" alt="" style="width: 2.75rem;margin: 0 auto;" class="img-radius" />
              <p class="f-11">{{ item.text }}</p>
            </div>
          </div>
        </div>
      </van-cell-group>
      <div class="computed-box">
        <div >{{form_tip.tip}}</div>
      </div>
      <div class="flex-j-sa m-t-10 padding-10">
        <van-button @click="toNextPage" plain round color="var(--themeBaseColor)" block style="width: 10rem;">取消</van-button>
        <van-button @click="submit" :disabled="uploadIng" round color="var(--themeBaseColor)" block style="width: 10rem;">{{ uploadIng ? `正在提交，${videoProgress}%`: "提交" }}</van-button>
      </div>
    </div>

    <van-popup v-model="showAgreement" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" :close-on-click-overlay="false">
      <div class="pop-base-title">数字人使用协议</div>
      <div class="pop-base-content t-l padding-10">
        <div v-html="body_clone_agreement"></div>
      </div>
      <div class="pop-base-bottom" @click="showAgreement = false">
        <van-button round color="var(--themeBaseColor)" type="danger" block style="height: 40px;">我已知晓并同意</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imgPath: '',
      name: "",
      tempFilePath: "",
      showAgreement: false,
      body_clone_agreement: "",

      errDomo: [
        {
          text: "多张面孔",
          icon: 10
        },
        {
          text: "面部过大",
          icon: 11
        },
        {
          text: "面部被遮挡",
          icon: 12
        },
        {
          text: "未检测到面孔",
          icon: 13
        }
      ],
      uploadIng: false, //是否正在上传
      videoProgress: 0,
      fileList: [],
      upload_file_max_size: "",
      upload_file_tip: "",
      cover_img: "",
      form_tip: {}
    };
  },

  created() {
    this.business_id = this.$route.query.business_id;
    this.getData();
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    async getData() {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.body-clone",
        {
          business_id: this.$route.query.business_id || 0
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.imgPath = this.$store.state.imgPath;
      this.body_clone_agreement = data.body_clone_agreement;
      this.upload_file_max_size = data.upload_file_max_size;
      this.upload_file_tip = data.upload_file_tip;
      this.showAgreement = true;
      this.getInterestsTip();
    },
    toNextPage() {
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.replace(this.fun.getUrl("aiCreateSpacePortal", {}, {}));
      }
    },
    chooseMedia() {
      this.$refs.uploader.chooseFile();
    },
    handleFileRead(file) {
      // 设置最大允许的大小为 5MB (5 * 1024 * 1024 bytes)
      const isLt5M = (file.file.size / 1024 / 1024) > this.upload_file_max_size;
      console.log((file.file.size / 1024 / 1024),3333333,file);
      if (isLt5M) {
        this.$toast(this.upload_file_tip);
        return;
      }
      // 生成临时URL
      this.tempFilePath = URL.createObjectURL(file.file);
      this.tempFile = file.file;
      // if (file.file) {
      //   this.TempFile = file.file;
      //   this.createVideoThumbnail(file.file);
      // }
    },
    createVideoThumbnail(file) {
      const video = document.createElement("video");
      video.preload = "metadata";
      video.muted = true; // 确保视频静音
      video.autoplay = true; // 自动播放

      video.onloadedmetadata = () => {
        video.currentTime = 0; // 设置视频时间为0秒
      };

      video.onseeked = () => {
        const canvas = document.createElement("canvas");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        this.thumbnail = canvas.toDataURL(); // 获取封面图的base64编码
        this.uploadFile('cover_img', this.thumbnail);
      };

      video.onerror = error => {
        console.error("Video error:", error);
      };

      video.src = URL.createObjectURL(file);
      video.load(); // 手动触发视频加载
    },
    uploadFile(type, file) {
      console.log(type,file,333333333333)
      // file, thumbnailBase64
      const formData = new FormData();
      let url = this.fun.getRealUrl("upload.uploadPic");
      if(type == 'cover_img') {
        // 将base64编码的封面图转换为Blob对象
        const blob = this.dataURItoBlob(file);
        formData.append("file", blob);
      } else {
        url = this.fun.getRealUrl("plugin.ai-create.frontend.controllers.create.body-clone.create");
        formData.append("file", file);
        formData.append("name", this.name);
        formData.append("business_id", this.$route.query.business_id || 0);
        formData.append("cover_img", this.cover_img);
        console.log(formData,'4444444444')
      }
      axios
        .post(url, formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          },
          onUploadProgress: (onUploadProgress) => {
            if(type !== 'cover_img') {
              this.videoProgress = Math.round((onUploadProgress.loaded * 100) / onUploadProgress.total) == 100 ? 99 : Math.round((onUploadProgress.loaded * 100) / onUploadProgress.total)
              console.log(this.videoProgress,4343434,onUploadProgress);
            }
          }
        })
        .then(response => {
          if(!response.data.result) {
            this.$toast(response.data.msg);
            return
          }
          console.log("Upload success:", response.data);
          if(type == 'cover_img') {
            this.cover_img = response.data.data.img_url;
            this.uploadFile('video', this.tempFile);
          } else {
            this.uploadIng = false;
            this.$toast("上传成功", "success");
            // this.toNextPage();
            this.$router.push(this.fun.getUrl("aiCreateVideoList", {}, { business_id: this.business_id,isArrShow : 1, title: "分身管理"}));
          }
          this.videoProgress = 100
        })
        .catch(error => {
          console.error("Upload error:", error);
        });
    },
    dataURItoBlob(dataURI) {
      // 将base64编码的字符串转换为Blob对象
      const byteString = atob(dataURI.split(",")[1]);
      const mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },

    submit() {
      if (!this.tempFilePath) {
        this.$toast("请上传分身视频", "error");
        return;
      }
      if (!this.name) {
        this.$toast("请设置分身名称", "error");
        return;
      }
      if(this.uploadIng) return;
      this.uploadIng = true;

      this.createVideoThumbnail(this.tempFile);//有封面，先上传封面
      // if (this.thumbTempFilePath) {
      //   this.onRead_1(); //有封面，先上传封面
      // } else {
      //   this.uploadFile(); //提交上传
      // }
    },
    // 前置校验方法
    async beforeRead (event) {
        return new Promise((resolve, reject) => {
        if (event.size > 10 * 1024 * 1024) {
          this.$toast('文件不能超过10MB');
          reject();
        } else {
          resolve();
        }
      });
    },
    uploadImage(file) {
      if (file.size > 10 * 1024 * 1024) {
          this.$toast('文件不能超过10MB');
          return false
      }

      const img = new Image();
      img.src = file.content;
      img.onload = () => {
        const ratio = Math.max(
          img.width / img.height,
          img.height / img.width
        )
        if (ratio > 2) {
          this.$toast('图片长宽比不能超过2:1')
          this.fileList = []
          this.cover_img = ""
          return false
        }
        
        if (img.width > 4096 || img.height > 4096) {
          this.$toast('图片最大边长不能超过4096px')
          this.fileList = []
          this.cover_img = ""
          return false
        }

        let uploadLoading = this.$toast.loading({
          message: "上传中",
          duration: 0
        });

        let fd = new FormData();
        fd.append("file", file.file);
        axios
          .post(this.fun.getRealUrl("upload.uploadPic"), fd, {
            headers: { "Content-Type": "multipart/form-data" }
          })
          .then(
            ({data}) => {
              console.log(data,'datadata',data.result);
              if (data.result == 1) {
                this.cover_img = data.data.img_url;
                // this.fileList.push(data.data.img_url)
              } else {
                // this.fileList = []
                this.$toast(data.msg)
              }
              uploadLoading.clear();
            }
          )
          .catch(() => {
            this.$toast('上传失败')
            uploadLoading.clear();
          });

        console.log(ratio,'ratioratioratio');
      };
    },
    // 删除文件
    onDelete() {
      this.fileList = []
    },
    async getInterestsTip() {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.center.index.get-Interests-tip",
        {
          business_id: this.$route.query.business_id || 0,
          interests_type: 2
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.form_tip = data;
      console.log(result, msg, data,2222,this.form_tip)
    },
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.pop-base-class .pop-base-title {
  margin: 18px 12px 12px !important;
  font-size: 16px !important;
  font-weight: bold !important;
  text-align: left !important;
}
.pop-base-class .pop-base-content {
  min-height: 45vh;
  max-height: 60vh;
  overflow: scroll;
  padding: 0 0px 60px;
}
.pop-base-class .pop-base-bottom {
  padding: 10px 14px;
  background: #ffffff;
}
.color-00001C {
  color: #00001C;
}
.color-AAAAB3 {
  color: #AAAAB3;
}
.color-F15353 {
  color: #F15353;
}
.bg-fff {
  background-color: #ffffff;
}
.bg-F8F8F8 {
  background-color: #F8F8F8;
}
.img-radius {
  border-radius: 50%;
  overflow: hidden;
}
.border-radius-10 {
  border-radius: 0.625rem;
  overflow: hidden;
}

.tabs-custom-class {
  background-color: #f5f5f5;
}

.tabs-custom-class .van-tabs__line {
  bottom: 6px !important;
  width: 20px !important;
}

.m-t-10 {
  margin-top: 0.625rem !important;
}

.padding-10 {
  padding: 0.625rem;
}

.padding-12 {
  padding: 0.75rem;
}

.padding-top-12 {
  padding-top: 0.75rem;
}

.padding-bottom-12 {
  padding-bottom: 0.75rem;
}

.padding-left-6 {
  padding-left: 0.375rem;
}
.gird-4 {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  text-align: center;
}

.headTop {
  padding: 1.5rem 0.75rem 4.6875rem;
  background-image: -webkit-gradient(linear, left top, left bottom, from(var(--themeBaseColor)), to(#f5f5f5));
  background-image: -webkit-linear-gradient(var(--themeBaseColor), #f5f5f5);
  background-image: linear-gradient(var(--themeBaseColor), #f5f5f5);
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.headTop .himg {
  width: 7.1875rem;
  height: 7.1875rem;
  margin: 0 auto;
}

.headTop .himg img {
  width: 100%;
  height: 100%;
  border-radius: 100%;
}

.headTop .himg video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.computed-box {
  margin-top: 0.875rem;
  font-weight: 400;
  font-size: 0.8125rem;
  color: #6E6E79;
  line-height: 1.3125rem;
  padding: 0 0.625rem;
  .computed-tip {
    color: #015EF5;
  }
}
</style>
